/*
    This file is part of jTopaz.
    http://gcl.cis.udel.edu/projects/jtopaz
    Copyright (C) 2009 University of Delaware

    jTopaz is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    jTopaz is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of                                                        
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with jTopaz.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
Contains functions that are run when the extension is loaded.
i.e. copying jar files, prompting for hosts/passwords, instantiating java objects, loading directory contents
*/
var username;
var passwd;
var myProxyServer;
var usingMyProxy = false;
var client;
var listContents;
var transferCount = 0;
var lastUpdated=0;
var infoClientStarted=false;
var transferClientStarted=false;
var uploadClientStarted=false;
var loginDone=false;
var classLoader;
var gridFTPServer;
var gridFTPServerPort;



/*
called once the user clicks the connect button.
asks for host to connect to, calls initalize function on that host
(lots of this borrowed from nsIGridLogin.js)
*/
function promptForHost(){
       
    defineOSType();
    
    //Loads the applet into the iframe.  User should be then prompted to trust it.
    var appletFrame = document.getElementById("appletFrame");
    var appletSrc = "file://" + topazDirPath + "chrome" + sep + "content" + sep + "applet.html";
    appletFrame.setAttribute("src", appletSrc);
    
    var host;
    var port;

    //show the prompt, get the values
    var hostport=prompt("Enter server:port or just server :", "midas.damsl.cis.udel.edu:2822");

    var i=hostport.indexOf(":");
    if(i==-1){
	host=hostport;
	port=2811;
    }
    else{
	host=hostport.slice(0,i);
	port=parseInt(hostport.slice(i+1));
    }
      	//initalize does a lot of start up stuff.
    initialize(host, port);
}


/*
Calls MyProxyLogin.  (Can probably get rid of this now, did a lot more when copying jars/loading classes was necessary).
*/
function initialize(hostName, portNum) {
	
	//should change this, don't really need this object anymore
	var GridFTPClient = Components.classes['@pmcclory.gcl.udel.edu/gridftpclient;1']
                                    .getService().wrappedJSObject;
	//save the host in the object
	GridFTPClient.host = hostName;
    

	GridFTPServer = hostName;
	GridFTPServerPort = portNum;

	usingMyProxy = document.getElementById("myproxy").hasAttribute("checked");
	if(usingMyProxy){
	    //prompt for myproxy info if we are using myProxy
	    //otherwise we are goin anonymous!
	    promptForMyProxy();
	    var applet = window.frames.appletFrame;
	    applet.myProxyLogin(myProxyServer, username, passwd);
	}
	
	//log in to get the proxy from the myproxy server

	myProxyCheck();
	
}


/*
Checks if the proxy has been obtained from the myproxy server.  If so starts the authentication process.
*/
function myProxyCheck() {
	
                                  
     var applet = window.frames.appletFrame;
     var status;
                            
                           
     //get the status   
     if(usingMyProxy){
	 status = applet.getMyProxyStatus();
     }
     else{
	 status = "success";
     }

     //if logged in or going anonymous
     if (status == "success") {
	 applet.remoteLogin(GridFTPServer, GridFTPServerPort);
	 applet.transferClientLogin(GridFTPServer, GridFTPServerPort);
	 applet.uploadClientLogin(GridFTPServer, GridFTPServerPort);

	 //then display the contents
	 displayContents();	
	 return "success";
     }
     
     //if there was an error alert
     else if (status == "error") {
	 alert("failed logging onto server");
	 return "failed";
     }
     
     //otherwise, value isn't set yet, loop
     else {
	 //alert("not done");
	 setTimeout("myProxyCheck();", 1000);	
     }	
}

function myProxyTry(count, myProxyServer, username, passwd) {
	var applet = window.frames.appletFrame;
	
	//alert("trying to connect to myproxy");
	applet.myProxyLogin(myProxyServer, username, passwd);
	var result = myProxyCheck();
	count++;
	if (result == "success")
		return "success";
	else if (result == "undefined") {
		while(result == "undefined") {
			result = myProxyCheck();
		}
	}
	else if (count < 3) {
		var date = new Date();
		var curDate = null;

		do { curDate = new Date(); } 
		while(curDate-date < 3000);	
		//alert("trying again (after 3 seconds)");
		myProxyTry(count, myProxyServer, username, passwd);
		return;
	}
	else if (result == "failed") {
		alert("failed");
		return "failed";
	}
}
/*
method for displaying the remote/local directory contents in the browser.
calls buildLocalTree and buildTree
*/
function displayContents() {

	//get the localContents xul element
	listContents = window.document.getElementById("localContents");
	
	//buildLocalTree with the localContents elt as the parent
	currentLocalDir = java.lang.System.getProperty("user.home");
	//alert(currentLocalDir);
	if (OStype == "mac") {
		buildLocalTree(currentLocalDir, listContents);
	}
	
	else if (OStype == "windows") {
		buildLocalTree(currentLocalDir, listContents);
	}
	
	else if (OStype == "linux") {
		buildLocalTree(currentLocalDir, listContents);
	}
	//displays that remotecontents are loading
	loading(window);
	
	//checks if connected, once connected it calls buildTree
	checkIfConnected();
	
	return;
}

/*
checks if the infoClient has connected with the remote host.  if so calls method to display the remote contents.
*/
function checkIfConnected() {
	
    var applet = window.frames.appletFrame;

                                    
     //check if the info client is connected
     var connected = applet.getLoginStatus();
     
     //alert(connected);
    //get the remoteContents xul element
    listContents = window.document.getElementById("remoteContents");
     
     //if connected
     if(connected == "success") {
     	//remove the loading message
     	removeLoading();
	 
     	//call to build the remote tree
     	buildTree(listContents, true);
     }
     
     //if failed, alert and return
     else if (connected == "failed") {
     	alert("error connecting to remote location");	
     }
     
     //otherwise loop
     else {
     	setTimeout("checkIfConnected()", 2500);
     }
}


/*
given a tree name, returns the actual tree in the document
*/
function getTree(treeName) {
	var tree = document.getElementById(treeName);
	return tree;
}

/*
given a tree name, returns the index that is currently selected.
*/
function getSelectedIndex(treeName) {
	var tree = getTree(treeName);
	var index = tree.view.selection.currentIndex;
	return index;
}

/*
given a tree, returns the value of the currently selected element
*/
function getSelectedValue(treeName, index) {
	var tree = getTree(treeName);
	try {
		var value = tree.view.getCellValue(index, tree.columns.getFirstColumn());
		return value;
	}
	catch(e) {
		alert("something went wrong");
		alert(e);
	}
}

/*
given a tree, returns the text of the currently selected index
*/
function getSelectedText(treeName, index) {
	var tree = getTree(treeName);
	return tree.view.getCellText(index, tree.columns.getFirstColumn());
}

/*
displays that the remote contents are loading
*/
function loading(window) {
	
	//get the remote contents tree
	var remoteContents = document.getElementById("remoteContents");
	
	/*
	create an element.  set it as saying loading.  append it to the tree
	*/
	var treeItem = document.createElement("treeitem");
	treeItem.setAttribute("id", "loading item");
	var treeRow = document.createElement("treerow");
	var treeCell = document.createElement("treecell");
	treeCell.setAttribute("id", "loading");
	treeCell.setAttribute("label", "Loading remote contents");
	treeRow.appendChild(treeCell);
	treeItem.appendChild(treeRow);
	remoteContents.appendChild(treeItem);
}

/*
removes the loading message
*/
function removeLoading() {
	
	var loading = window.document.getElementById("loading item");
	var parent = loading.parentNode;
	parent.removeChild(loading);	
}


var topazDir = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties)
                .get("ProfD", Components.interfaces.nsILocalFile);

var sep;
var OStype;
function defineOSType() {
	//alert(topazDir.path);
	if (topazDir.path.indexOf("C:") == 0) {
		//alert("windows");
		OStype = "windows";
		sep = "\\"
		topazDirPath = topazDir.path + sep + "extensions" + sep + "{29eadb1b-9c38-475e-ac9d-a34d707d34e3}" + sep;
		//alert(topazDirPath);
	}
	else if (topazDir.path.indexOf("/Users/") == 0) {
		//alert("mac");
		OStype = "mac";
		topazDirPath = topazDir.path + "/extensions/{29eadb1b-9c38-475e-ac9d-a34d707d34e3}/";
		sep = "/";
	}
	else if (topazDir.path.indexOf("/home") == 0) {
		OStype = "linux";
		topazDirPath = topazDir.path + "/extensions/{29eadb1b-9c38-475e-ac9d-a34d707d34e3}/";
		sep = "/";
	}
}
var topazDirPath;

/*
prompts user for myproxy info.  code borrowed from nsIGridLogin.js
*/
function promptForMyProxy() {
	
	
	var windowMediator = Components.classes['@mozilla.org/appshell/window-mediator;1']
                              .getService(Components.interfaces.nsIWindowMediator);

	var win = windowMediator.getMostRecentWindow( "navigator:browser" );
    

	var reg = new Object();
	 	win.openDialog("chrome://sample/content/gamaSelect.xul", "_blank",
                        "scrollbars,resizable,chrome,modal=yes,dialog=yes", reg);
	if( reg.newRegistry != null )
	{
	    myProxyServer = reg.newRegistry;
	    //getCACert(myProxyServer);
	    promptUsernameAndPassword();
	    return true;
	}


	alert("myProxy problem");
	return false;
}

/*
prompts user for myproxy username/password.
borrowed from nsIGridLogin.js
*/
function promptUsernameAndPassword()
{


	const PROMPTSERVICE_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
	const nsIPromptService = Components.interfaces.nsIPromptService;
	this.promptService = Components.classes[PROMPTSERVICE_CONTRACTID].getService(nsIPromptService);
	
	username = {value:""};
	passwd = {value:""};
	var check = {value:true};

	var okorcancel = this.promptService.promptUsernameAndPassword(null, 'Login Information', 'Enter Username and Password', username, passwd, null, check );

	if(  !username.value || !passwd.value )
	    return false;

	username = username.value;
	passwd = passwd.value;
}
